import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TimerRecord } from './entities/timer-record.entity';
import { CreateTimerRecordDto } from './dto/create-timer-record.dto';
import { User } from '../users/entities/user.entity';
import { OperationType } from '../operation-types/entities/operation-type.entity';

@Injectable()
export class TimerRecordsService {
  constructor(
    @InjectRepository(TimerRecord)
    private timerRecordRepository: Repository<TimerRecord>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(OperationType)
    private operationTypeRepository: Repository<OperationType>,
  ) {}

  async create(createTimerRecordDto: CreateTimerRecordDto): Promise<TimerRecord> {
    const user = await this.userRepository.findOne({
      where: { id: createTimerRecordDto.userId },
    });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const operationType = await this.operationTypeRepository.findOne({
      where: { id: createTimerRecordDto.operationTypeId },
    });
    if (!operationType) {
      throw new NotFoundException('操作类型不存在');
    }

    if (createTimerRecordDto.endTime) {
      if (!createTimerRecordDto.duration) {
        const start = new Date(createTimerRecordDto.startTime);
        const end = new Date(createTimerRecordDto.endTime);
        createTimerRecordDto.duration = Math.floor((end.getTime() - start.getTime()) / 1000);
      }
      createTimerRecordDto.status = createTimerRecordDto.status || 'completed';
    } else {
      createTimerRecordDto.status = createTimerRecordDto.status || 'running';
    }

    const timerRecord = this.timerRecordRepository.create({
      ...createTimerRecordDto,
      user,
      operationType,
    });

    return this.timerRecordRepository.save(timerRecord);
  }

  async findAll(): Promise<TimerRecord[]> {
    return this.timerRecordRepository.find({
      relations: ['user', 'operationType'],
      order: { createdAt: 'DESC' },
    });
  }

  async findByUserId(userId: number): Promise<TimerRecord[]> {
    return this.timerRecordRepository.find({
      where: { user: { id: userId } },
      relations: ['user', 'operationType'],
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: number): Promise<TimerRecord> {
    const timerRecord = await this.timerRecordRepository.findOne({
      where: { id },
      relations: ['user', 'operationType'],
    });
    if (!timerRecord) {
      throw new NotFoundException('计时记录不存在');
    }
    return timerRecord;
  }

  async remove(id: number): Promise<void> {
    const result = await this.timerRecordRepository.delete(id);
    if (result.affected === 0) {
      throw new NotFoundException('计时记录不存在');
    }
  }

  async findByEmployeeId(employeeId: string): Promise<TimerRecord[]> {
    return this.timerRecordRepository.find({
      where: { user: { employeeId } },
      relations: ['user', 'operationType'],
      order: { createdAt: 'DESC' },
    });
  }
}